'use strict'

import {
  app,
  BrowserWindow,
  ipcMain,
  // Tray,
  Menu,
  // isMac,
  // Notification,
  // clipboard,
  // globalShortcut,
  dialog,
  screen
  // systemPreferences
} from 'electron'
// import { autoUpdater } from 'electron-updater'
import fixPath from 'fix-path'
import db from '../datastore'
import pkg from '../../package.json'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
if (process.env.DEBUG_ENV === 'debug') {
  global.__static = require('path').join(__dirname, '../../static').replace(/\\/g, '\\\\')
}

let mainWindow
let settingWindow
let miniWindow
let tray
let menu
let contextMenu

const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`
const settingWinURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080/#setting`
  : `file://${__dirname}/index.html#setting/upload`
const miniWinURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080/#mini-page`
  : `file://${__dirname}/index.html#mini-page`

// fix the $PATH in macOS
fixPath()

function createContextMenu () {
  contextMenu = Menu.buildFromTemplate([
    {
      label: '关于',
      click () {
        dialog.showMessageBox({
          title: 'PicGo',
          message: 'PicGo',
          detail: `Version: ${pkg.version}\nAuthor: Molunerfinn\nGithub: https://github.com/Molunerfinn/PicGo`
        })
      }
    },
    {
      label: '打开详细窗口',
      click () {
        if (settingWindow === null) {
          createSettingWindow()
          settingWindow.show()
        } else {
          settingWindow.show()
          settingWindow.focus()
        }
        if (miniWindow) {
          miniWindow.hide()
        }
      }
    },
    /* {
      label: '选择默认图床',
      type: 'submenu',
      submenu
    }, */
    {
      label: '打开更新助手',
      type: 'checkbox',
      checked: db.get('settings.showUpdateTip').value(),
      click () {
        const value = db.read().get('settings.showUpdateTip').value()
        db.read().set('settings.showUpdateTip', !value).write()
      }
    },
    {
      label: '重启应用',
      click () {
        app.relaunch()
        app.exit(0)
      }
    },
    {
      role: 'quit',
      label: '退出'
    }
  ])
}

/*function createTray () {
  const menubarPic = process.platform === 'darwin' ? `${__static}/menubar.png` : `${__static}/menubar-nodarwin.png`
  tray = new Tray(menubarPic)
  tray.on('right-click', () => {
    if (window) {
      window.hide()
    }
    createContextMenu()
    tray.popUpContextMenu(contextMenu)
  })
  tray.on('click', (event, bounds) => {
    if (process.platform === 'darwin') {
      let img = clipboard.readImage()
      let obj = []
      if (!img.isEmpty()) {
        // 从剪贴板来的图片默认转为png
        const imgUrl = 'data:image/png;base64,' + Buffer.from(img.toPNG(), 'binary').toString('base64')
        obj.push({
          width: img.getSize().width,
          height: img.getSize().height,
          imgUrl
        })
      }
      toggleWindow(bounds)
      setTimeout(() => {
        window.webContents.send('clipboardFiles', obj)
      }, 0)
    } else {
      if (window) {
        window.hide()
      }
      if (settingWindow === null) {
        createSettingWindow()
        settingWindow.show()
      } else {
        settingWindow.show()
        settingWindow.focus()
      }
      if (miniWindow) {
        miniWindow.hide()
      }
    }
  })
  // toggleWindow()
}*/

const createWindow = () => {
  if (mainWindow) {
    mainWindow.show()
    return
  }

  const deviceWidth = screen.getPrimaryDisplay().workAreaSize.width
  const deviceHeight = screen.getPrimaryDisplay().workAreaSize.height
  const minWidth = 1200
  const minHeight = 800
  let appWidth = Math.min(deviceWidth, minWidth)
  let appHeight = Math.min(deviceHeight, minHeight)
  let appX = Math.round(Math.abs(deviceWidth - minWidth - 15) * 0.5)
  let appY = Math.round(Math.abs(deviceHeight - minHeight) * 0.5)

  /* Initial window options */
  mainWindow = new BrowserWindow({

    resizable: true,
    show: false,
    fullscreenable: true,
    useContentSize: false,
    vibrancy: 'ultra-dark',
    webPreferences: {
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      backgroundThrottling: false
    },
    // transparent: true, // 透明，无顶部条
    // frame: false
    x: appX,
    y: appY,
    width: appWidth,
    height: appHeight,
    minWidth: appWidth,
    minHeight: appHeight,
  })

  mainWindow.loadURL(winURL)
  // createMenu()
  // mainWindow.removeMenu()
  Menu.setApplicationMenu(null)

  // webContents = mainWindow.webContents

  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  /* 交互 */
  /*
  mainWindow.on('close', e => {
    e.preventDefault();
    mainWindow.minimize();
    mainWindow.webContents.send('toStop');
  });

  mainWindow.on('blur', () => {
    mainWindow.webContents.send('blur');
    mainWindow.webContents.send('toBlur');
  });

  ipcMain.on('fakeClose', () => {
    mainWindow.minimize();
    mainWindow.webContents.send('toStop');
  });
  */
  return mainWindow
}

const createMiniWidow = () => {
  if (miniWindow) {
    return false
  }
  let obj = {
    height: 64,
    width: 64,
    show: process.platform === 'linux',
    frame: false,
    fullscreenable: false,
    skipTaskbar: true,
    resizable: false,
    transparent: process.platform !== 'linux',
    icon: `${__static}/logo.png`,
    webPreferences: {
      backgroundThrottling: false,
      nodeIntegration: true,
      nodeIntegrationInWorker: true
    }
  }

  if (db.read().get('settings.miniWindowOntop').value()) {
    obj.alwaysOnTop = true
  }

  miniWindow = new BrowserWindow(obj)

  miniWindow.loadURL(miniWinURL)

  miniWindow.on('closed', () => {
    miniWindow = null
  })
  return miniWindow
}

const createSettingWindow = () => {
  const options = {
    height: 450,
    width: 800,
    show: false,
    frame: true,
    center: true,
    fullscreenable: false,
    resizable: false,
    title: 'PicGo',
    vibrancy: 'ultra-dark',
    transparent: true,
    titleBarStyle: 'hidden',
    webPreferences: {
      backgroundThrottling: false,
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      webSecurity: false
    }
  }
  if (process.platform !== 'darwin') {
    options.show = false
    options.frame = false
    options.backgroundColor = '#3f3c37'
    options.transparent = false
    options.icon = `${__static}/logo.png`
  }
  settingWindow = new BrowserWindow(options)

  settingWindow.loadURL(settingWinURL)

  settingWindow.on('closed', () => {
    settingWindow = null
    if (process.platform === 'linux') {
      app.quit()
    }
  })
  createMenu()
  createMiniWidow()
  return settingWindow
}

const toggleWindow = (bounds) => {
  if (window.isVisible()) {
    window.hide()
  } else {
    showWindow(bounds)
  }
}

const showWindow = (bounds) => {
  window.setPosition(bounds.x - 98 + 11, bounds.y, false)
  window.webContents.send('updateFiles')
  window.show()
  window.focus()
}

const createMenu = () => {
  // if (process.env.NODE_ENV !== 'development') {
  const template = [
    {
      label: '文件',
      submenu: [
        {label: '导入Excel', accelerator: 'CmdOrCtrl+P', selector: 'import:'},
        { type: 'separator' },
        {
          label: '退出',
          accelerator: 'CmdOrCtrl+Q',
          click () {
            app.quit()
          }
        }
      ]
    },
    /*{
      label: '编辑',
      submenu: [
        {label: 'Undo', accelerator: 'CmdOrCtrl+Z', selector: 'undo:'},
        {label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', selector: 'redo:'},
        {type: 'separator'},
        {label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:'},
        {label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:'},
        {label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:'},
        {label: 'Select All', accelerator: 'CmdOrCtrl+A', selector: 'selectAll:'}
      ]
    },*/
    {
      label: '帮助',
      submenu: [
        {
          label: '关于我们',
          role: 'about'
        },
        {
          label: '开发工具',
          role: 'toggledevtools'
        }
      ]
    }
  ]
  menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
  // }
}

if (process.platform === 'win32') {
  app.setAppUserModelId(pkg.build.appId)
}

if (process.env.XDG_CURRENT_DESKTOP && process.env.XDG_CURRENT_DESKTOP.includes('Unity')) {
  process.env.XDG_CURRENT_DESKTOP = 'Unity'
}

app.on('ready', () => {
  createWindow()
  // mainWindow.webContents.openDevTools()
  // createSettingWindow()
  /*if (process.platform === 'darwin' || process.platform === 'win32') {
    createTray()
  }*/
  /*
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
  */
  // db.read().set('needReload', false).write()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

app.on('will-quit', () => {
  // 快捷键注销
  // globalShortcut.unregisterAll()
})

/**
 * 边框
 */
/*
import { app, BrowserWindow, ipcMain } from 'electron';
// 窗口最小化
ipcMain.on('min-window', () => {
  mainWindow.minimize();
});
// 窗口最大化
ipcMain.on('max-window', () => {
  if (mainWindow.isMaximized()) {
    mainWindow.restore();
  } else {
    mainWindow.maximize();
  }
});
// 关闭
ipcMain.on('close-window', () => {
  mainWindow.close();
});
// 导出下载
ipcMain.on('download', (event, downloadPath) => {
  mainWindow.webContents.downloadURL(downloadPath);
  mainWindow.webContents.session.once('will-download', (event, item) => {
    item.once('done', (event, state) => {
      // 成功的话 state为completed 取消的话 state为cancelled
      mainWindow.webContents.send('downstate', state);
    });
  });
});
*/

// 在主线程下，通过ipcMain对象监听渲染线程传过来的getPrinterList事件
ipcMain.on('getPrinterList', (event) => {
  // 在主线程中获取打印机列表
  const list = mainWindow.webContents.getPrinters()
  // 通过webContents发送事件到渲染线程，同时将打印机列表也传过去
  mainWindow.webContents.send('gotPrinterList', list)
})

// 在主线程下，通过ipcMain对象监听渲染线程传过来的getPrinterList事件
/*ipcMain.on('showAppInfo', (event) => {
  dialog.showMessageBox({
    buttons: ['Yes'],
    type: 'none',
    title: '福彩3D',
    message: `版本: ${pkg.version}\n作者: 歪八二\n描述：用于计算福彩3D的方式。`
  })
})*/

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/**
 * 自动更新
 */
/*
app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
*/
/*
ipcMain.on('update', () => { // e, arg
  console.log('update')
  checkForUpdates()
})

// 阻止程序关闭自动安装升级
autoUpdater.autoInstallOnAppQuit = false
// const feedUrl = {url: "http://127.0.0.1:5500/win32", type: 'custom'}; // 更新包位置
const feedUrl = 'http://127.0.0.1:5500/win32' // 更新包位置

let checkForUpdates = () => {
  // 配置安装包远端服务器
  autoUpdater.setFeedURL(feedUrl)

  // 下面是自动更新的整个生命周期所发生的事件
  autoUpdater.on('error', (message) => {
    sendUpdateMessage('error', message)
  })
  // 检查更新
  autoUpdater.on('checking-for-update', (message) => {
    sendUpdateMessage('checking-for-update', message)
  })
  // 有可用更新
  autoUpdater.on('update-available', (message) => {
    sendUpdateMessage('update-available', message)
  })
  // 已经最新
  autoUpdater.on('update-not-available', (message) => {
    sendUpdateMessage('update-not-available', message)
  })

  // 更新下载进度事件
  autoUpdater.on('download-progress', (progressObj) => {
    sendUpdateMessage('downloadProgress', progressObj)
  })

  // 更新下载完成事件
  /!* eslint-disable *!/
  autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) => {
    sendUpdateMessage('isUpdateNow')
    ipcMain.on('updateNow', (e, arg) => {
      autoUpdater.quitAndInstall()
    })
  })
  /!* eslint-enable *!/

  // 更新出错
  autoUpdater.on('error', message => {
    sendUpdateMessage('error', message)
  })

  // 执行自动更新检查
  autoUpdater.checkForUpdates()
}

// 主进程主动发送消息给渲染进程函数
function sendUpdateMessage (message, data) {
  console.log({ message, data })
  mainWindow.webContents.send('message', { message, data })
}*/
